package com.chii.gateway.service.impl;

import com.alibaba.fastjson.JSON;
import com.chii.gateway.routes.RedisRouteDefinitionRepository;
import com.chii.gateway.service.IRouteService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
public class RouteService implements IRouteService {
    private Logger logger = LogManager.getLogger(RedisRouteDefinitionRepository.class);

    private static final String GATEWAY_ROUTES = "gateway:routes";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private Map<String, RouteDefinition> routeDefinitionMaps = new HashMap<>();

    @PostConstruct
    private void initRoute() {
        logger.info("loadRouteDefinition, 开始初使化路由");
        Set<String> gatewayKeys = stringRedisTemplate.keys(GATEWAY_ROUTES + "*");
        if (CollectionUtils.isEmpty(gatewayKeys)) {
            return;
        }
        stringRedisTemplate.opsForHash().entries(GATEWAY_ROUTES).forEach((key, val) -> {
            logger.info("初使化路由, gatewayKeys：{},key：{},val：{}", gatewayKeys, key, val);
            routeDefinitionMaps.put((String) key, JSON.parseObject((String) val, RouteDefinition.class));
        });
        logger.info("共初使化路由信息：{}", routeDefinitionMaps.size());
    }


    @Override
    public Collection<RouteDefinition> getRouteDefinitions() {
        return routeDefinitionMaps.values();
    }

    @Override
    public boolean save(RouteDefinition routeDefinition) {
        routeDefinitionMaps.put(routeDefinition.getId(), routeDefinition);
//        stringRedisTemplate.opsForHash().put(GATEWAY_ROUTES, routeDefinition.getId(),
//                JSON.toJSONString(routeDefinition));
        logger.info("新增路由1条：{},目前路由共{}条", routeDefinition, routeDefinitionMaps.size());
        return true;
    }

    @Override
    public boolean delete(String routeId) {
        routeDefinitionMaps.remove(routeId);
//        stringRedisTemplate.opsForHash().delete(GATEWAY_ROUTES, routeId);
        logger.info("删除路由1条：{},目前路由共{}条", routeId, routeDefinitionMaps.size());
        return true;
    }
}
